<template>
  <!-- ----------------------------------------------
                        发布公告
    ----------------------------------------------- -->
  <div class="fabu">
    <div class="fabu_title" @click="handleAnnounceClick">发布公告</div>
    <el-dialog title="发布公告" :visible.sync="dialogTableVisible">
      <el-table
        :data="
          Noticedata.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        border
      >
        <el-table-column
          property="name"
          label="区域名称"
          width="400"
          align="center"
        ></el-table-column>
        <el-table-column
          property="phoneNumber"
          label="物业电话"
          width="400"
          align="center"
        ></el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <span class="demonstration">调整每页显示条数</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Noticedata.length"
        >
        </el-pagination>
      </div>
      公告信息：<el-input
        type="textarea"
        autosize
        v-model="textarea"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClick">发布公告</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
var map;
var source;
var layer;
var drawLine = null;
const resultBaseUrl = 'gdbp://MapGisLocal/wuhan/sfcls/'; // gdbp://MapGisLocal/wuhan_1/sfcls/居民区
var resultname = null;
var affectedArea = [];
var announcePageSize = 5;
var resultClipLayer;
import { createDraw } from '../../utils/Draw';
export default {
  name: 'fabu',
  data() {
    return {
      Noticedata: [],
      dialogTableVisible: false,
      textarea:
        '您好, xxx道路近期维修, 时间为xxxx年xx月-xxxx年xx月, 请及时规划出行路线，避免对您的出行造成影响。',
      currentPage: 1,
      pageSize: 5,
      user_id: '',
      NoticeName: '',
    };
  },
  created() {
    this.username = this.$cookies.get('username');
    this.$http.get('/report?username=' + this.username).then((res) => {
      this.user_id = res.result.user_id;
      // console.log('id',this.user_id);
    });
  },
  methods: {
    handleAnnounceClick() {
      var that = this;
      map = this.$store.state.map;
      /* 1、激活画布,获取坐标 */
      source = new ol.source.Vector({
        wrapX: false,
      });
      layer = new ol.layer.Vector({
        source,
      });
      map.addLayer(layer);
      drawLine = createDraw({
        type: 'LineString',
        source,
        callback: announceDrawend,
      });
      map.addInteraction(drawLine);
      //交互式绘制结束的回调
      function announceDrawend(e) {
        console.log(e);
        const points = e.feature.getGeometry().getCoordinates();
        //将绘制的多边形每个点坐标转换成mapgis点对象, 并存入arc_points数组
        //每次绘制结束, arc_points存储的都是最新的几何对象的信息

        const arc_points = points.map((item) => {
          return new Zondy.Object.Point2D(item[0], item[1]);
        });
        //console.log(arc_points)
        singleBuffAnalysis(0.001, arc_points);
      }
      //缓冲分析
      function singleBuffAnalysis(radius, arc_points) {
        const gArc = new Zondy.Object.Arc(arc_points);
        //构成线的折线
        const gAnyLine = new Zondy.Object.AnyLine([gArc]);
        //设置线要素的几何信息
        const gline = new Zondy.Object.GLine(gAnyLine);
        //设置要素的几何信息
        const fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] });

        //设置属性结构
        const regAttStr = new Zondy.Object.CAttStruct({
          FldName: ['ID', '周长', 'LayerID'],
          FldNumber: 3,
          FldType: ['FldLong', 'FldDouble', 'FldLong'],
        });
        const values = [1, 0.132101984752282, 8];
        //实例化CAttDataRow类
        const valuesRow = new Zondy.Object.CAttDataRow(values, 1);

        //实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
        const featureBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
          ip: 'localhost',
          port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
          //设置要素缓冲分析左半径
          leftRad: radius,
          //设置要素缓冲分析右半径
          rightRad: radius,
        });

        resultname = resultBaseUrl + 'roadsBuffer' + Date.now();

        /*设置缓冲分析参数*/
        //设置几何信息
        featureBufBySR.sfGeometryXML = JSON.stringify([fGeom]);
        //设置属性结构
        featureBufBySR.attStrctXML = JSON.stringify(regAttStr);
        //设置属性值
        featureBufBySR.attRowsXML = JSON.stringify([valuesRow]);
        //设置追踪半径
        featureBufBySR.traceRadius = 0.0001;
        //设置缓冲结果的名称以及存放地址
        featureBufBySR.resultName = resultname;

        //调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析，AnalysisSuccess为回调函数。
        featureBufBySR.execute(bufferAnalysisSuccess, 'post', false, 'json');
      }
      //缓冲分析成功的回调
      function bufferAnalysisSuccess(data) {
        map.removeInteraction(drawLine);
        if (data.succeed) {
          //将结果图层添加到地图视图中显示
          // const resultBufferLayer = new Zondy.Map.GdbpLayer(
          //   'smart-city',
          //   [resultname],
          //   {
          //     ip: 'localhost',
          //     port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
          //     isBaseLayer: false,
          //   }
          // )
          // map.addLayer(resultBufferLayer)
          //裁剪
          //console.log(data)
          const clspath = data.results[0].Value;
          resultname = resultBaseUrl + 'roadsClip' + Date.now();
          //实例化ClipByLayer类
          const clipParam = new Zondy.Service.ClipByLayer({
            ip: 'localhost',
            port: '6163',
            //源简单要素类的URL
            srcInfo1: 'gdbp://MapGisLocal/wuhan/sfcls/居民区',
            //裁剪框简单要素类的URL
            srcInfo2: clspath,
            //设置结果URL
            desInfo: resultname,
            infoOptType: 0,
          });
          //调用基类的execute方法，执行图层裁剪分析。AnalysisSuccess为结果回调函数
          clipParam.execute(clipSuccess, 'post', false, 'json', clipError);
        } else {
          alert('缓冲区分析失败，请检查参数！');
        }
      }
      //裁剪成功的回调
      function clipSuccess(data) {
        //console.log(data)
        map.removeLayer(resultClipLayer);
        if (data.succeed) {
          //将结果图层添加到地图视图中显示
          resultClipLayer = new Zondy.Map.GdbpLayer(
            'resultClipLayer',
            [resultname],
            {
              ip: 'localhost',
              port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
              //isBaseLayer: false,
              crossOrigin: 'Anonymous',
            }
          );
          map.addLayer(resultClipLayer);
          queryByAttribute(resultname);
        } else {
          alert('叠加分析失败，请检查参数！');
        }
      }

      function clipError(e) {
        console.log(e);
      }
      //通过gdbp查询要素图层
      function queryByAttribute(gdbpUrl) {
        //初始化查询结构对象，设置查询结构包含几何信息
        const queryStruct = new Zondy.Service.QueryFeatureStruct();
        queryStruct.IncludeGeometry = true;
        //实例化查询参数对象
        const queryParam = new Zondy.Service.QueryByLayerParameter(gdbpUrl, {
          resultFormat: 'json',
          struct: queryStruct,
        });
        queryParam.where = '1>0';
        //实例化地图文档查询服务对象
        const queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
          ip: 'localhost',
          port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089
        });
        //执行查询操作，querySuccess为查询回调函数
        queryService.query(queryAnnounceSuccess);
      }
      //查询成功回调
      function queryAnnounceSuccess(result) {
        that.dialogTableVisible = true;
        //console.log(result)
        if (!result.SFEleArray) {
          alert('没有受影响的居民区');
          source.clear();
          drawLine = null;
          map.removeLayer(resultClipLayer);
          map.on('click', addPopup);
          return;
        }
        console.log(result);
        that.Noticedata;
        var arr1 = [];
        result.SFEleArray.forEach((element) => {
          var data = {};
          (data.name = element.AttValue.slice(4, 5)),
            (data.phoneNumber = element.AttValue.slice(5, 6));
          that.Noticedata.push(data);
        });
        console.log('aa', that.Noticedata);
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    handleClick() {
      const NoticeName = this.Noticedata.map((item) => {
        console.log(item.name);
        return item.name;
      }).join(',');
      console.log(NoticeName);
      this.$http
        .post('/notice', {
          user_id: this.user_id,
          notice_content: this.textarea,
          affected_area: NoticeName,
        })
        .then((res) => {
          console.log(res);
          this.$message.success('发布公告成功');
        });
      this.dialogTableVisible = false;
    },
  },
};
</script>
<style scoped>
.fabu {
  position: absolute;
  top: 18px;
  left: 1023px;
  width: 90px;
  height: 35px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.6);
  font-weight: 700;
  cursor: pointer;
  text-align: center;
  line-height: 35px;
  z-index: 1;
}
.fabu:hover {
  background-color: #dbdbdb;
}
.fabu_title {
  display: inline;
  font-weight: 700;
  color: #7c8196;
}
.fabu_title:hover {
  color: white;
}
</style>
